import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Button,
  Checkbox,
  Menu,
  Modal,
  Tree,
  message,
  Badge,
  Divider,
  Radio,
  Popconfirm,
} from 'antd';
import TableList from '@/components/TableList';
import ChoosePerson from '@/components/BindPerson/ChoosePerson';
import HasUser from '@/components/BindPerson/HasUser';
import styles from '../search.less';
const FormItem = Form.Item;
const CheckboxGroup = Checkbox.Group;
const RadioGroup = Radio.Group;
const {TreeNode} = Tree;
const DirectoryTree = Tree.DirectoryTree;
const statusMap = ['success', 'error'];
const status = ['启用', '禁用'];

const CreateForm = Form.create()(props => {
  const {
    modalVisible,
    form,
    addDataFn,
    updateFn,
    handleModalVisible,
    text,
    orgTreeData,
    setUsercode,
    userCode,
    disableValue,
    disableCopy,
    saveChecked,
    copyChecked,
    printChecked,
    onReadonlyEditRight,
    handleBindUserVisible,
    groupMember,
    handleHasUserVisible,
  } = props;
  const handleReadEdit = (e) => {
    onReadonlyEditRight(e)
  }
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      if(!text && !(groupMember.length&&groupMember[0].userCode)){
        message.warning('请选择人员')
        return;
      }
      const jurisdiction = fieldsValue.jurisdiction;
      const obj = {}
      jurisdiction&&jurisdiction.length&&jurisdiction.map((v) => {
        if(v==2){
          obj.saveAsRight = 0
        }
        if(v==3){
          obj.copyRight = 0
        }
        if(v==4){
          obj.printRight = 0
        }
      })

      if(text) {
        updateFn(Object.assign(obj,fieldsValue),text)
      }else{
        addDataFn(Object.assign(obj,fieldsValue));
      }
    });
  };
  const onSelect = (info,e) => {
    const userCode = e.node.props.userCode;
    setUsercode(userCode)
  }

  const loop = data => data.map((item) => {
    if (item.children) {
      return (
        <TreeNode key={item.id} title={item.name} {...item}>
          {loop(item.children||[])}
        </TreeNode>
      );
    }
    return <TreeNode key={item.id} title={item.name} {...item}/>;
  });

  const defaultId = text&&text.userCode+ '';

  const initialValue = [];
  if(text&&text.userCode){
    if(text.saveAsRight == 0){
      initialValue.push(2)
    }
    if(text.copyRight == 0){
      initialValue.push(3)
    }
    if(text.printRight == 0){
      initialValue.push(4)
    }
  }

  return (
    <Modal
      destroyOnClose
      width={800}
      title={text?'编辑权限配置':'新增权限配置'}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >

      <Form>
        <Row gutter={16}>
          <Col md={24}>
          <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} label="编辑权限：">
           {form.getFieldDecorator('readonlyEditRight',
             {rules: [{ required: true,message:'请选择编辑权限'}],initialValue:text&&text.readonlyEditRight})(
             <RadioGroup onChange={handleReadEdit}>
               <Radio value={0}>只读</Radio>
               <Radio value={1}>编辑</Radio>
             </RadioGroup>
           )}
         </FormItem>
         </Col>
         <Col md={24}>
         <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} label="权限操作：">
           {form.getFieldDecorator('jurisdiction', {initialValue})(
             <CheckboxGroup>
               <Checkbox checked={copyChecked} key="copyKey" disabled={disableCopy} value={3}>禁止复制</Checkbox>
               <Checkbox checked={saveChecked} key="saveKey" disabled={disableValue} value={2}>禁止另存</Checkbox>
               <Checkbox checked={printChecked} key="printKey"disabled={disableValue} value={4}>禁止打印</Checkbox>
             </CheckboxGroup>
           )}
         </FormItem>
         </Col>
         <Col md={24}>
          <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} label="状态" style={{display: text == null ? 'none' : 'block',}}>
            {form.getFieldDecorator('status', {initialValue: text&&text.status
            })(<Radio.Group>
              <Radio value={0}>
                启用
              </Radio>
              <Radio value={1}>
                禁用
              </Radio>
            </Radio.Group>)}
          </FormItem>
          </Col>

          {!text?<Col md={24}>
            <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} label="人员设置">
            {form.getFieldDecorator('userCodeList',{initialValue: text&&text.userCodeList||[]})(
              <Fragment>
                <Button type="primary" onClick={() => handleBindUserVisible(true)} >请选择</Button>
                <div>{groupMember&&groupMember.length?groupMember.slice(0,3).map((v,i) => {
                return <span key={i} style={{marginRight:'20px',}}>{v.userName}{/*<Icon type="close-circle" onClick={() => deleteGMember(i)} />*/}</span>
              }):null}{groupMember&&groupMember.length&&groupMember.length>3?'...':''}
              {groupMember&&groupMember.length&&groupMember.length>0?<a onClick={() => handleHasUserVisible(true)} style={{marginLeft:25}}>查看已选人员</a>:null}
              </div>
              </Fragment>
            )}              
            </FormItem>
          </Col>:null}
        </Row>
      </Form>
    </Modal>
  );
});


/* eslint react/no-multi-comp:0 */
@connect(({ editPerson, loading }) => ({
  editPerson,
  loading: loading.models.editPerson,
}))


@Form.create()
class editPerson extends PureComponent {
  state = {
   modalVisible: false,
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    stepFormValues: {},
    text: {},
    orgTreeData: [],
    userCode: '',
    bindUserVisible: false, //绑定用户
    personData: {}, //人员数据
    groupMember: [],
    hasUserVisible: false,
    //权限编辑
    disableValue: false,
    disableCopy: false,
    saveChecked: false,
    copyChecked: false,
    printChecked: false,
  };

  columns = [
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '所属组织',
      dataIndex: 'parentName',

    },
    {
      title: '编辑权限',
      dataIndex: 'rightStr',

    },
    {
      title: '状态',
      /* render(val) {
        return statusValue[val.status];
      }*/

      dataIndex: 'status',
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]} />;
      },
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleModalVisible(true,text)}>编辑</a>
          <Divider type="vertical" />
         {/* <Popconfirm title="是否要删除此行？" onConfirm={() => this.handleDeleteData(text.id)}>
            <a>删除</a>
          </Popconfirm>*/}

          <a onClick={() => this.handleDeleteData(text.id)}>删除</a>
        </Fragment>
      ),
    },
  ];
  handleDeleteData = (id) => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.deleteItem(id),
    });
  };
  setUsercode = (v) => {
    this.setState({
      userCode: v,
    })
  }

  batchDelete = (rows=[]) => {
    const ids = rows.map((item) => {
      return item.id;
    }).join(",");
    this.handleDeleteData(ids); //批量删除
  };

  // 删除方法
  deleteItem(id) {
    const { dispatch } = this.props;
    const values = {
     id
    };
    dispatch({
      type: 'editPerson/remove',
      payload: values,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({
            title: res.msg,
          });
          this.pageList();
          this.setState({selectedRows: []})
        }else {
          Modal.error({
            title: '操作失败',
            content: res.msg,
          });
        }
      },
    });
  }

  // 分页查询列表
  pageList(data,pageSize=10,pageNum=0) {
    const { dispatch } = this.props;
    const values = {
      name: data&&data.name||'',
      readonlyEditRight: data&&data.readonlyEditRight,
      copyRight: data&&data.copyRight,
      saveAsRight: data&&data.saveAsRight,
      printRight: data&&data.printRight,
      userType: 1,
      pageSize: pageSize, //分页每页条数
      pageNum: pageNum, //分页页码
    };
    dispatch({
      type: 'editPerson/queryList',
      payload: values,
    });
  }

  componentDidMount() {
    this.pageList();
    this.getTree();//组织树请求
  }

    // 点击树查询人员接口
  getList(res,pageSize=5,pageNum=0) {
    const { dispatch } = this.props;
    const values = {
      type: res && res.type || '',
      orgId: res && res.orgId,
      id: res && res.id || '',
      pageSize: pageSize,
      pageNum: pageNum,
      userName:res&& res.userName||'',
      userCode:res&& res.userCode||'',
    };
    dispatch({
      type: 'editPerson/getList',
      payload: values,
      callback: (obj) => {
        if(obj.result == "ok") {
          this.setState({
            personData: obj.data,
          })
        }
      },
    });
  }

  getTree() {
    const { dispatch } = this.props;
    dispatch({
      type: 'editPerson/getTree',
    });
  }

handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

   handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
     const obj = {};
     if(fieldsValue.authority == "0"){
        obj.readonlyEditRight = 0;
     }else if(fieldsValue.authority == "1"){
        obj.readonlyEditRight = 1;
     }
     else if(fieldsValue.authority == "2"){
        obj.saveAsRight = 0;
     }
     else if(fieldsValue.authority == "3"){
        obj.copyRight = 0;
     }
     else if(fieldsValue.authority == "4"){
        obj.printRight = 0;
     }else{
        obj.readonlyEditRight = '';
        obj.saveAsRight = '';
        obj.copyRight = '';
        obj.printRight = '';
     }
    this.pageList(Object.assign(fieldsValue,obj));
    this.setState({
        formValues: Object.assign(fieldsValue,obj),
    })
    });
  };
// 新增弹框的显示和隐藏
  handleModalVisible = (flag,text) => {
    const newArr = [];
    this.setState({
      modalVisible: !!flag,
      text: text,
      userCode: text&&text.userCode?text.userCode:''
    });
    if(!flag) {
      this.setState({
        groupMember: newArr,
      })
    }
    if(text&&flag) {
      newArr.push(text);
      this.setState({
        groupMember: newArr,
      })
      if(text.readonlyEditRight==0){
        this.setState({
          disableValue: true,
          disableCopy: false,
        })
      }else{
        this.setState({
          disableValue: false,
          disableCopy: true,
        })
      }
    }
  };

  // 更新接口
  updateFn = (fields,text) => {
    const { dispatch } = this.props;
    // const userCode = this.state.groupMember.length?this.state.groupMember[0].userCode:text.userCode;
    const params = {
      userType: 1,
      // userCode: userCode?userCode:text.userCode,
      id: text.id,
      status: fields.status,
      readonlyEditRight: fields.readonlyEditRight,
      copyRight: fields.readonlyEditRight==0?fields.copyRight:'',
      saveAsRight: fields.readonlyEditRight==1?fields.saveAsRight:'',
      printRight: fields.readonlyEditRight==1?fields.printRight:'',
    }
    dispatch({
      type: 'editPerson/update',
      payload: params,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({
            title: res.msg,
          });
          this.pageList();
        }else {
          Modal.error({
            title: '操作失败',
            content: res.msg,
          });
        }
      },
    });
    this.handleModalVisible();
  };

  // 增加接口
  addDataFn = (fields) => {
    const { dispatch } = this.props;
    // const userCode = this.state.groupMember[0].userCode;
     const { groupMember } = this.state;
    const userCodeList = groupMember&&groupMember.length&&groupMember.map((v)=>{
      return v.userCode
    }).join(",")
    const params = {
        userType: 1,
        readonlyEditRight: fields.readonlyEditRight,
        copyRight: fields.readonlyEditRight==0?fields.copyRight:'',
        saveAsRight: fields.readonlyEditRight==1?fields.saveAsRight:'',
        printRight: fields.readonlyEditRight==1?fields.printRight:'',
        userCodeList,
        // userCode,
    }
    dispatch({
      type: 'editPerson/add',
      payload: params,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({
            title: res.msg,
          });
          this.pageList();
        }else {
          Modal.error({
            title: '操作失败',
            content: res.msg,
          });
        }
      },
    });
    this.handleModalVisible();
  };

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="姓名">
              {getFieldDecorator('name')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="编辑权限">
              {getFieldDecorator('authority')(<Select placeholder="请选择" style={{ width: '100%' }}>
                <Option value="5">全部</Option>
                <Option value="0">只读</Option>
                <Option value="1">编辑</Option>
                <Option value="2">禁止另存为</Option>
                <Option value="3">禁止复制</Option>
                <Option value="4">禁止打印</Option>
              </Select>)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderSimpleForm() : this.renderSimpleForm();
  }

  handleStandardTableChange(pagination, filters, sorter) {
    const {formValues} = this.state;
  // 分页请求
  this.pageList(formValues,pagination.pageSize,pagination.current-1);
  }

   // 已选择成员详情弹框
  handleHasUserVisible = (flag) => {
    this.setState({
      hasUserVisible: !!flag,
    });
  };

  deleteGMember = (userCode) => {
    const { groupMember } = this.state;
    let copyGM = [...groupMember];
    copyGM.map((v,i) => {
      if(v.userCode == userCode) {
        copyGM.splice(i,1);
      }
    })
    this.setState({
      groupMember: copyGM,
    })
  }

    // 绑定用户弹框显示和隐藏
  handleBindUserVisible = (flag,selectedRows) => {
    this.setState({
      bindUserVisible: !!flag,
    });
    if(!flag){
      const { groupMember } = this.state;
      // const concatArr = selectedRows?selectedRows:groupMember;
      const concatArr = selectedRows?groupMember.concat(selectedRows):groupMember;
      // 去重
      const result = [];
      let obj = {};
      for(var i =0; i<concatArr.length; i++){
         if(!obj[concatArr[i].userCode]){
            result.push(concatArr[i]);
            obj[concatArr[i].userCode] = true;
         }
      }
      this.setState({
        personData: {},
        groupMember: result,
      })
    }
  };
  onReadonlyEditRight = e => {
    const value = e.target.value;
    if(value == 0){
      this.setState({
        // rightDo: [2,4],

        saveChecked: true,
        copyChecked: false,
        printChecked: true,
        disableValue: true,
        disableCopy: false,
      })
    }else{
      this.setState({
        // rightDo: [],

        saveChecked: false,
        copyChecked: false,
        printChecked: false,
        disableValue: false,
        disableCopy: true,
      })
    }

  }

  render() {
    const {
      editPerson: { data, treeDataList },
      loading,
    } = this.props;
    const {
      selectedRows,
      modalVisible,
      updateModalVisible,
      stepFormValues,
      text,
      orgTreeData,
      userCode,
      bindUserVisible,
      personData,
      disableValue,
      disableCopy,
      saveChecked,
      copyChecked,
      printChecked,
      groupMember,
      hasUserVisible,
    } = this.state;
    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="remove">删除</Menu.Item>
      </Menu>
    );
    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      handleBindUserVisible: this.handleBindUserVisible.bind(this),
      addDataFn: this.addDataFn,
      updateFn: this.updateFn,
      setUsercode: this.setUsercode,
      onReadonlyEditRight: this.onReadonlyEditRight,
      handleHasUserVisible: this.handleHasUserVisible,
    };
    const BindUserMethods = {
      handleBindUserVisible: this.handleBindUserVisible.bind(this),
      getList: this.getList.bind(this),
    }
    const hasUserMethods = {
      handleHasUserVisible: this.handleHasUserVisible.bind(this),
      deleteGMember: this.deleteGMember.bind(this),
    }

    return (
      <Card bordered={false}>
        <CreateForm
          {...parentMethods}
          modalVisible={modalVisible}
          text={text}
          orgTreeData={orgTreeData}
          userCode={userCode}
          saveChecked={saveChecked}
          copyChecked={copyChecked}
          printChecked={printChecked}
          disableValue={disableValue}
          disableCopy={disableCopy}
          groupMember={groupMember}
        />
        {hasUserVisible?<HasUser
           {...hasUserMethods}
           hasUserVisible={hasUserVisible}
           groupMember={groupMember}
        />:null}
        <ChoosePerson
            {...BindUserMethods}
            bindUserVisible={bindUserVisible}
            treeDataList={treeDataList}
            personData={personData}
            text={text}
          />
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
          <div className={styles.tableListOperator}>
            <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
              新增
            </Button>
            {selectedRows.length > 0 && (
              <span>
                   <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
                </span>
            )}
          </div>
          <TableList
            className={styles.tdPadding}
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange.bind(this)}
            rowKey={record => record.id}
          />
        </div>
      </Card>
    );
  }
}

export default editPerson;
